<template>

  <div class="box">
    <ul class="loginOptions">
      <li>
        <!-- <span>手机号：</span> -->
        <el-input type="text" v-model="phone" placeholder="请输入手机号" />
        <!-- <span class="prompt">手机号格式不正确</span> -->
      </li>

      <li>
        <!-- <span> 验证码： </span> -->
        <el-input type="text" v-model="code" placeholder="请输入验证码">
          <template #append>
            <el-button @click="showSlide" :disabled="pendingCode.disabled" :style="{ color: pendingCode.color }">{{
              pendingCode.title }}</el-button>
          </template>

        </el-input>




        <!-- <span class="prompt">验证码不正确</span> -->
      </li>
      <li class="login-btn">
          <el-button type="danger" @click="login">登录</el-button>
      </li>

    </ul>
    <div class="agreement">
      <div>
        <el-checkbox class="deepcheck" v-model="agreed">登录即代表你同意<span style="color: #c90000;">《鹿线AI用户协议》</span></el-checkbox>
      </div>
    </div>
    <SlideSPlit class="slide-split" v-if="slideShow" :bigImg="imgInfo.bigImageBase64" :smImg="imgInfo.smallImageBase64"
      :w="imgInfo.bigWidth" :h="imgInfo.bigHeight" :l="imgInfo.smallWidth" :smallHeight="imgInfo.smallHeight"
      @sliderJudge="onJudge" @request-event="getImage"></SlideSPlit>



  </div>
</template>
<script lang='ts' setup>
import SlideSPlit from  '@/components/SlideSplit/index.vue'
import { ref , reactive ,defineEmits,onBeforeUnmount} from 'vue'
import { 
  getImageCode, 
  verifyImageCode, 
  loginVerification } from '@/api/login'



const phone = ref('')
const code = ref('')
// 显示滑块
const slideShow = ref(false)
// 滑块组件要的参数
const imgInfo = reactive({
  bigWidth: 300,
  bigHeight: 180,
  bigImageBase64: '',
  smallWidth: 0,
  smallHeight: 0,
  smallImageBase64: ''
})



// 显示滑块—+
const showSlide=async  ()=>{
  let imginfo =  await getImage()
  slideShow.value = imginfo;
}

let reg = reactive({
  mobile: { rules: /^1[3-9]\d{9}$/, err: '请输入正确手机号' },
  captcha: { rules: /\d{6}/, err: '请输入六位验证码' }
})

//请求图片数据
const getImage = async ()=>{
  if (!reg.mobile.rules.test(phone.value)) {
    ElNotification({
      type: 'error',
      message:reg.mobile.err
    })
    return
  }

  try {
    let res = await getImageCode(phone.value)
    console.log(res.data);
    // if (res) return
    Object.assign(imgInfo, res.data)
    return res
  } catch{
    console.log('错误');
  }

}

//滑动结束用户操作验证
const onJudge = async (left:string) => { 
  let res = await verifyImageCode(left, phone.value)
  console.log('验证结果',res);
  if (res.code != 0){
    // 验证没通过，重新拿滑动内容
    getImage()
  }else{
    slideShow.value = false
    pendingCodeBtn(true)

  }
}

const pendingCode = reactive<{
  title: string;
  time: number;
  disabled: boolean;
  // timer: NodeJS.Timeout | null; //找不到nodeJS的命名空间
  timer: number| undefined;  //浏览器环境下 定时器类型为 number
  color: string;
}>({
  title: '获取验证码',
  time: 60,
  disabled: false,
  timer: undefined,
  color: ''
});


const pendingCodeBtn = (isTrue: boolean = false) => {

  if (isTrue) {
    // 重置倒计时  
    pendingCode.time = 60;
    pendingCode.title = `获取验证码${pendingCode.time}s`;
    pendingCode.disabled = false;
    // 清除之前的定时器（如果有）  
    if (pendingCode.timer) {
      clearInterval(pendingCode.timer);
      pendingCode.timer = undefined
    }

    // 设置新的定时器  

      pendingCode.timer = setInterval(() => {
        console.log('定时');
        
      pendingCode.time--;
      pendingCode.title = `获取验证码${pendingCode.time}s`;
      if (pendingCode.time <= 0) {
        pendingCode.disabled = false;
        clearInterval(pendingCode.timer);
        pendingCode.timer = undefined;
        pendingCode.time = 60; // 可选：重置时间到初始值，或保持为0直到用户再次请求  
        pendingCode.color = '';
        pendingCode.title = '获取验证码'; // 可选：重置标题  
      }else{
        pendingCode.disabled = true;//定时期间禁止重复点击
        pendingCode.color = 'red'
      }

    }, 1000); // 每秒更新一次  

  } else {

    // 如果不需要重置，则不执行任何操作（或根据需要处理）  

  }

};  

//登录成功关闭主窗口
const emit = defineEmits(['close'])

// 协议
const agreed = ref<boolean>(false)



// 登录验证
import { userInfo } from '@/hooks/user';
import {  ElNotification } from 'element-plus';
const login =  () => {

  if (!agreed){
    ElNotification({
      type:'error',
      message:'请同意用户协议'
    })
    return
  }
  

  loginVerification(
    phone.value,
    code.value
  ).then(
    (ress)=>{

      if(ress.code == 0){
        if (pendingCode.timer) {
      clearInterval(pendingCode.timer);
      pendingCode.timer = undefined
    }
        emit('close')
        ElNotification({
          showClose: true,
          message: '登录成功',
          type: 'success'
        })
        userInfo(ress.data.token)
        emit('close')
      }else{
        ElNotification({
          showClose: true,
          message: ress.errorMessage,
          type: 'error'
        })
      }
  },
(rej)=>{
  console.log('rej',rej);
}
)
}

onBeforeUnmount(()=>{
  if (pendingCode.timer) {
      clearInterval(pendingCode.timer);
      pendingCode.timer = undefined
    }
})


</script>
<style scoped lang='scss'>

.box {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.slide-split{
  position: absolute;
  box-shadow: 0px 0px 5px 5px rgba(0, 0, 0, 0.5);
  z-index: 99999;
}

.loginOptions{
  width: 354px;
}
.loginOptions li{
  display: flex;
  position: relative;
  margin:  30px 0 ;
  align-items: center;
  span{
    margin-left: 10px;
  }
input:focus{
    border: 1px solid pink;
    box-sizing: border-box;
}

.prompt{
  color: red;
  position: absolute;
  bottom: -14px;
  left: 70px;
  font-size: 12px;
}
}
  .login-btn {
                  height: 52px;
                  margin-bottom: 20px;
                  border-radius: 11px;
                  .el-button {
                    width: 100%;
                    height: 52px;
                    font-size: 23px;
                    color: #FFFFFF;
                    background: #C90000;
                  }
                }
 input[type='number']{
    width: 200px;
    height: 30px;
    background-color: aliceblue;
    padding-left: 10px;
    box-sizing: border-box;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

input[type="number"] {
  -moz-appearance: textfield;
}

::v-deep .is-focus{
box-shadow: 0 0 0 1px #c90000 inset;
}
</style>
